import shutil
from pathlib import Path

d_list = [r'D:']


# 递归检查上级空目录,最上层无文件目录
def check_p_empty_dir(path):
    par = path.parent
    file_list = []
    for p in par.glob('**/*'):
        if p.is_file():
            file_list.append(p)
            return path
    if len(file_list) == 0:
        return check_p_empty_dir(par)


for d in d_list:
    if Path(d).exists():
        print("=" * 50)
        print("检查目录:", d)
        target_directory = Path(d)
        empty_folders = []

        for folder_path in target_directory.glob('**/*'):
            if folder_path.is_dir():
                try:
                    _ = next(folder_path.iterdir(), None)  # 尝试获取第一个子项，如果存在则说明非空，直接跳出循环
                    if _ is not None:
                        continue  # 发现第一个子项，跳过当前目录继续下一个
                except OSError:
                    print(f"{folder_path} 访问异常")
                    continue
                # 如果没有进入上面的continue，说明是空目录
                empty_folders.append(check_p_empty_dir(folder_path))
                print(folder_path)

        print(f"找到 {len(empty_folders)} 个空目录")
        if empty_folders:
            print("是否删除空目录？")
            if input("y/n: ").lower() == "y":
                for x in empty_folders:
                    try:
                        shutil.rmtree(x)
                        # x.rmdir()
                    except OSError:
                        print(f"{x} 删除失败")
                    except Exception as e:
                        print(f"{x} 删除失败: {e}")
            else:
                exit()
